{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os, sys\n",
    "import time\n",
    "import datetime\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import math\n",
    "from math import radians, cos, sin, asin, sqrt \n",
    "import random\n",
    "\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.ticker import MultipleLocator, FormatStrFormatter\n",
    "from matplotlib.patches import Ellipse, Circle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "\n",
    "hexagon_grid_table=pd.read_csv('hexagon_grid_table.csv',header=None,\n",
    "                            names = ['Grid_id','v1_lng','v1_lat',\\\n",
    "                                    'v2_lng','v2_lat',\\\n",
    "                                    'v3_lng','v3_lat',\\\n",
    "                                    'v4_lng','v4_lat',\\\n",
    "                                    'v5_lng','v5_lat',\\\n",
    "                                    'v6_lng','v6_lat'])\n",
    "\n",
    "hexagon_grid_table=hexagon_grid_table.dropna()\n",
    "\n",
    "\n",
    "\n",
    "X=list(hexagon_grid_table['v1_lng'])+list(hexagon_grid_table['v2_lng'])+list(hexagon_grid_table['v3_lng'])+list(hexagon_grid_table['v4_lng'])+list(hexagon_grid_table['v5_lng'])+list(hexagon_grid_table['v6_lng'])\n",
    "\n",
    "Y=list(hexagon_grid_table['v1_lat'])+list(hexagon_grid_table['v2_lat'])+list(hexagon_grid_table['v3_lat'])+list(hexagon_grid_table['v4_lat'])+list(hexagon_grid_table['v5_lat'])+list(hexagon_grid_table['v6_lat'])\n",
    "# hexagon_grid_table\n",
    "# hexagon_grid_table.iloc[0,1]\n",
    "# for i in range(0,len(hexagon_grid_table)):\n",
    "#     if((hexagon_grid_table.iloc[i,1]>hexagon_grid_table.iloc[i,3])|(hexagon_grid_table.iloc[i,2]>hexagon_grid_table.iloc[i,4])):\n",
    "#         print('No1')\n",
    "#         print(i)\n",
    "#     if((hexagon_grid_table.iloc[i,3]<hexagon_grid_table.iloc[i,5])|(hexagon_grid_table.iloc[i,4]>hexagon_grid_table.iloc[i,6])):\n",
    "#         print('No2')\n",
    "#         print(i)\n",
    "#     if((hexagon_grid_table.iloc[i,5]<hexagon_grid_table.iloc[i,7])|(hexagon_grid_table.iloc[i,6]>hexagon_grid_table.iloc[i,8])):\n",
    "#         print('No3')\n",
    "#         print(i)\n",
    "#     if((hexagon_grid_table.iloc[i,7]<hexagon_grid_table.iloc[i,9])|(hexagon_grid_table.iloc[i,8]<hexagon_grid_table.iloc[i,10])):\n",
    "#         print('No4')\n",
    "#         print(i)\n",
    "#     if((hexagon_grid_table.iloc[i,9]>hexagon_grid_table.iloc[i,11])|(hexagon_grid_table.iloc[i,10]<hexagon_grid_table.iloc[i,12])):\n",
    "#         print('No5')\n",
    "#         print(i)\n",
    "#     if((hexagon_grid_table.iloc[i,11]>hexagon_grid_table.iloc[i,1])|(hexagon_grid_table.iloc[i,12]<hexagon_grid_table.iloc[i,2])):\n",
    "#         print('No6')\n",
    "#         print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "               Grid_id     v1_lng    v1_lat     v2_lng    v2_lat     v3_lng  \\\n",
      "4803  3dfcc8aedf63ee3f  103.00165  29.98391  103.00559  29.98804  103.00352   \n",
      "4982  a7e5c9728d156772  103.00972  29.97689  103.01366  29.98102  103.01159   \n",
      "610   46d7d403e46e20c2  103.11772  30.29174  103.12168  30.29589  103.11961   \n",
      "3126  5523ac18acc59fda  103.14961  30.30960  103.15358  30.31375  103.15150   \n",
      "8423  fb665698fb213881  103.15150  30.31934  103.15547  30.32349  103.15340   \n",
      "...                ...        ...       ...        ...       ...        ...   \n",
      "4563  1f0bcd9362653a8f  116.49839  39.98117  116.50444  39.98540  116.50292   \n",
      "2075  815eca1eea7182da  117.12810  40.14128  117.13423  40.14549  117.13275   \n",
      "3927  3262a05e0aab92d1  117.94544  34.31559  117.95120  34.31966  117.94989   \n",
      "203   101ef48879c8a933  118.04835  24.48930  118.05347  24.49300  118.05231   \n",
      "4706  18ef3655da9320f3  120.36044  30.30984  120.36612  30.31372  120.36504   \n",
      "\n",
      "        v3_lat     v4_lng    v4_lat     v5_lng    v5_lat     v6_lng    v6_lat  \\\n",
      "4803  29.99362  102.99751  29.99506  102.99358  29.99093  102.99565  29.98535   \n",
      "4982  29.98660  103.00559  29.98804  103.00165  29.98391  103.00372  29.97833   \n",
      "610   30.30148  103.11358  30.30292  103.10962  30.29877  103.11169  30.29318   \n",
      "3126  30.31934  103.14547  30.32078  103.14150  30.31663  103.14357  30.31104   \n",
      "8423  30.32908  103.14736  30.33052  103.14339  30.32637  103.14547  30.32078   \n",
      "...        ...        ...       ...        ...       ...        ...       ...   \n",
      "4563  39.99161  116.49535  39.99360  116.48929  39.98937  116.49081  39.98315   \n",
      "2075  40.15172  117.12515  40.15375  117.11901  40.14954  117.12049  40.14330   \n",
      "3927  34.32597  117.94282  34.32820  117.93706  34.32413  117.93837  34.31783   \n",
      "203   24.49909  118.04603  24.50148  118.04091  24.49778  118.04207  24.49169   \n",
      "4706  30.32005  120.35827  30.32251  120.35258  30.31863  120.35366  30.31230   \n",
      "\n",
      "           c_lng      c_lat  Index  \n",
      "4803  102.999583  29.989485      1  \n",
      "4982  103.007655  29.982465      2  \n",
      "610   103.115650  30.297330      3  \n",
      "3126  103.147538  30.315190      4  \n",
      "8423  103.149432  30.324930      5  \n",
      "...          ...        ...    ...  \n",
      "4563  116.496867  39.987383   8514  \n",
      "2075  117.126622  40.147513   8515  \n",
      "3927  117.944130  34.321897   8516  \n",
      "203   118.047190  24.495390   8517  \n",
      "4706  120.359352  30.316175   8518  \n",
      "\n",
      "[8518 rows x 16 columns]\n"
     ]
    }
   ],
   "source": [
    "hexagon_grid_table=hexagon_grid_table.dropna()\n",
    "\n",
    "hexagon_grid_table['c_lng']=hexagon_grid_table.apply(lambda x:(x['v1_lng']+x['v2_lng']+x['v3_lng']\\\n",
    "                                                               +x['v4_lng']+x['v5_lng']+x['v6_lng'])/6,axis=1)\n",
    "\n",
    "hexagon_grid_table['c_lat']=hexagon_grid_table.apply(lambda x:(x['v1_lat']+x['v2_lat']+x['v3_lat']\\\n",
    "                                                               +x['v4_lat']+x['v5_lat']+x['v6_lat'])/6,axis=1)\n",
    "\n",
    "hexagon_grid_table['Index']=0\n",
    "hexagon_grid_table=hexagon_grid_table.sort_values(by=['c_lng','c_lat'])\n",
    "for i in range(0,len(hexagon_grid_table)):\n",
    "    hexagon_grid_table.iloc[i,15]=i+1\n",
    "    \n",
    "print(hexagon_grid_table)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def IntersectsSegment(ptx,pty,sptx,spty,eptx,epty): #0 for no, 1 for yes\n",
    "    #input: test point, start point , end point; all in format [lng, lat]\n",
    "    \n",
    "    if spty>pty and epty>pty: #segment over point\n",
    "        return 0\n",
    "    if spty<pty and epty<pty: #segment under point\n",
    "        return 0\n",
    "    if epty==pty: #end point is not counted\n",
    "        return 0\n",
    "    if sptx<ptx and eptx<ptx: #segment is on the left of test point\n",
    "        return 0\n",
    "    if spty==epty: #error\n",
    "        print('error')\n",
    "        return 0\n",
    "\n",
    "    xseg=eptx-(eptx-sptx)*(epty-pty)/(epty-spty) #lng of intersection\n",
    "    if xseg<ptx: #test point is on the right of segment\n",
    "        return 0\n",
    "    return 1  #test point intersects with segment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def WithinHex(ptx,pty,hexg): # 0 for no, 1 for yes\n",
    "    #input test point and hexagon, all in format [lng, lat]\n",
    "    \n",
    "    if pty==hexg[2]:# test point is the lowest vertax\n",
    "        if ptx==hexg[1]:\n",
    "            return 1\n",
    "        else:\n",
    "            return 0\n",
    "    \n",
    "    if pty==hexg[8]:# test point is the highest vertax\n",
    "        if ptx==hexg[7]:\n",
    "            return 1\n",
    "        else:\n",
    "            return 0\n",
    "        \n",
    "    sc=0 # # of intersections\n",
    "    for i in range(0,5):\n",
    "        sc=sc+IntersectsSegment(ptx,pty,hexg[(2*i+1)],hexg[(2*i+2)],hexg[(2*i+3)],hexg[(2*i+4)])\n",
    "    \n",
    "    sc=sc+IntersectsSegment(ptx,pty,hexg[11],hexg[12],hexg[1],hexg[2])\n",
    "    \n",
    "    \n",
    "\n",
    "    if sc%2==1:# if the # of intersections is odd\n",
    "        return 1 # test point is in the hexagon\n",
    "    else:# if the # of intersections is even\n",
    "        return 0 # test point is not in the hexagon"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ptx=hexagon_grid_table.iloc[0,3]-0.00001\n",
    "pty=hexagon_grid_table.iloc[0,4]\n",
    "hexg=hexagon_grid_table.iloc[0]\n",
    "# IntersectsSegment(ptx,pty,hexg[9],hexg[10],hexg[11],hexg[12])\n",
    "WithinHex(ptx,pty,hexg)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
